const Router = require('@koa/router')
const mongoose = require('mongoose')

const Vacation = mongoose.model('Vacation')


const router = new Router({
    prefix: '/vacation'
})
router.post('/add', async (ctx) => {
    let {
        vacationPerson,
        userId,
        startTime,
        endTime,
        reason,
        state
    } = ctx.request.body
    const vacation = new Vacation({
        vacationPerson,
        userId,
        startTime,
        endTime,
        reason,
        state
    })
    const res = await vacation.save()
    ctx.body = {
        data: res,
        msg: "新增请假记录",
        code: 200
    }
})
router.get('/list', async (ctx) => {
    // let {
    //     page = 1,
    //     size = 5,
    // } = ctx.query
    // page = Number(page)
    // size = Number(size)
    //跳过(page-1)*size条数据
    //获取分页数据
    // const list = await Vacation.find().skip((page - 1) * size).limit(size).exec()
    const list = await Vacation.find().sort({ _id: -1 }).exec()
    const total = await Vacation.countDocuments()
    ctx.body = {
        data: {
            list,
            total,
            // page,
            // size
        },
        code: 200,
        msg: '获取请假列表成功'
    }
})
/**管理层 */
router.post('/changeState', async (ctx) => {
    let {
        id,
        state
    } = ctx.request.body
    //查找id
    console.log('changestate_id', id);
    const one = await Vacation.findOne({
        _id: id
    })
    if (!one) {
        ctx.body = {
            msg: '不存在当前记录',
            code: 200
        }
    } else {
        one.state = state
        const res = await one.save() //更新状态
        if(state==0){
            msg="请假审批中"
        }else if(state==1){
            msg="请假已通过"
        }else{
            msg="请假被否决"
        }
        ctx.body = {
            data: res,
            msg: msg,
            code: 200
        }
    }
    // const res = await Vacation.update(
    //     {
    //         "_id": id
    //     },
    //     {
    //         $set: { "state": state }
    //     }
    // )

})
//删除操作 接口
router.delete('/:id', async (ctx) => {
    const {
        id
    } = ctx.params
    const delMsg = await Vacation.deleteOne({
        _id: id
    })
    ctx.body = {
        data: delMsg,
        code: 200,
        msg: '删除成功'
    }
})
router.post('/getVacationState', async (ctx) => {
    let {
        userId
    } = ctx.request.body
    const list = await Vacation.find({ userId: userId }).sort({ _id: -1 }).exec()
    //查找某userId的list
    ctx.body = {
        data: {
            list
        },
        code: 200,
        msg: '成功获取当前用户请假信息'
    }
})
module.exports = router